<!--
  @author: cqz
  @desc: 数据源下拉选择通用组件
  @date: 2020-12-22
-->
<template>
  <el-select ref="select" filterable placeholder="请选择数据源" clearable v-model="value" @clear="clearHandler" @change="changeHandle" style="width: 100%">
    <el-option-group
      v-for="group in srcList"
      :key="group.label"
      :label="group.label">
      <el-option
        v-for="item in group.options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-option-group>
  </el-select>
</template>

<script>
export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: Object
  },
  data () {
    return {
      srcList: []
    }
  },
  methods: {
    init (srcId, dbType) {
      this.srcList = []
      this.$http({
        url: this.$http.adornUrl(`/src/source/tree`),
        params: this.$http.adornParams({
          'type': dbType || ''
        }),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          for (var i = 0; i < data.tree.length; i++) {
            var item = data.tree[i]
            var srcCat
            if (item.isCat === 1) {
              srcCat = {label: item.name, options: [], id: item.id}
              this.srcList.push(srcCat)
            } else {
              srcCat = this.srcList.find(cat => (cat.id === item.parentId))
              srcCat.options.push({value: item.id, label: item.name})
              if (srcId === item.id) {
                this.$emit('change', srcId, item.name)
              }
            }
          }
        }
      })
    },
    // 数据源选中
    changeHandle (value) {
      this.$nextTick(() => {
        this.$emit('change', value, this.$refs['select'].selected.$options.propsData.label)
      })
    },
    clearHandler () {
      this.value = ''
      this.$emit('change')
    }
  }
}
</script>

